package com.bird.web.controller.system;

import cn.hutool.core.util.ObjectUtil;
import com.bird.common.annotation.Log;
import com.bird.common.constant.Constants;
import com.bird.common.enums.BusinessType;
import com.bird.common.utils.Assert;
import com.bird.common.utils.StringUtil;
import com.bird.framework.domain.Result;
import com.bird.framework.utils.SecurityUtils;
import com.bird.system.domain.entity.SysUserEntity;
import com.bird.system.domain.params.SysUserQueryParams;
import com.bird.system.domain.params.SysUserUpdateParams;
import com.bird.system.service.ISysPostService;
import com.bird.system.service.ISysRoleService;
import com.bird.system.service.ISysUserService;
import com.bird.web.controller.common.BaseController;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户信息
 *
 * @author bird
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
	@Autowired
	private ISysUserService userService;

	@Autowired
	private ISysRoleService roleService;

	@Autowired
	private ISysPostService postService;

	/**
	 * 获取用户列表
	 */
	@PreAuthorize("@ss.hasPermi('system:user:list')")
	@GetMapping("/list")
	public Result<PageInfo<SysUserEntity>> list(SysUserQueryParams user) {
		startPage();
		List<SysUserEntity> list = userService.selectUserList(user);
		return page(list);
	}

	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
	@PreAuthorize("@ss.hasPermi('system:user:export')")
	@GetMapping("/export")
	public Result export(SysUserQueryParams user) {
		List<SysUserEntity> list = userService.selectUserList(user);
		return null;
	}

	/**
	 * 根据用户编号获取详细信息
	 */
	@PreAuthorize("@ss.hasPermi('system:user:query')")
	@GetMapping(value = {"/", "/{userId}"})
	public Result getInfo(@PathVariable(value = "userId", required = false) Long userId) {
		Result ajax = ok();
		ajax.put("roles", roleService.selectRoleAll());
		ajax.put("posts", postService.selectPostAll());
		if (ObjectUtil.isNotNull(userId)) {
			ajax.put("user", userService.selectUserById(userId));
			ajax.put("postIds", postService.selectPostListByUserId(userId));
			ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
		}
		return ajax;
	}

	/**
	 * 新增用户
	 */
	@PreAuthorize("@ss.hasPermi('system:user:add')")
	@Log(title = "用户管理", businessType = BusinessType.INSERT)
	@PostMapping
	public Result add(@Validated @RequestBody SysUserUpdateParams user) {
		Assert.isTrue(Constants.User.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())), "新增用户{}失败，登录账号已存在", user.getUserName());
		if (StringUtil.isNotBlank(user.getPhonenumber())) {
			Assert.isTrue(Constants.User.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)), "新增用户{}失败，手机号码已存在", user.getUserName());
		}
		if (StringUtil.isNotBlank(user.getEmail())) {
			Assert.isTrue(Constants.User.NOT_UNIQUE.equals(userService.checkEmailUnique(user)), "新增用户{}失败，邮箱账号已存在", user.getUserName());
		}
		SysUserEntity covert = user.covert();
		covert.setCreateBy(SecurityUtils.getUsername());
		covert.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		return ok(userService.insertUser(covert));
	}

	/**
	 * 修改用户
	 */
	@PreAuthorize("@ss.hasPermi('system:user:edit')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping
	public Result edit(@Validated @RequestBody SysUserUpdateParams user) {
		userService.checkUserAllowed(user);
		if (StringUtil.isNotBlank(user.getPhonenumber())) {
			Assert.isTrue(Constants.User.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)), "新增用户{}失败，手机号码已存在", user.getUserName());
		}
		if (StringUtil.isNotBlank(user.getEmail())) {
			Assert.isTrue(Constants.User.NOT_UNIQUE.equals(userService.checkEmailUnique(user)), "新增用户{}失败，邮箱账号已存在", user.getUserName());
		}
		SysUserEntity covert = user.covert();
		covert.setUpdateBy(SecurityUtils.getUsername());
		return ok(userService.updateUser(covert));
	}

	/**
	 * 删除用户
	 */
	@PreAuthorize("@ss.hasPermi('system:user:remove')")
	@Log(title = "用户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
	public Result remove(@PathVariable Long[] userIds) {
		return ok(userService.deleteUserByIds(userIds));
	}

	/**
	 * 重置密码
	 */
	@PreAuthorize("@ss.hasPermi('system:user:edit')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/resetPwd")
	public Result resetPwd(@RequestBody SysUserUpdateParams user) {
		userService.checkUserAllowed(user);
		SysUserEntity covert = user.covert();
		covert.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		covert.setUpdateBy(SecurityUtils.getUsername());
		return ok(userService.resetPwd(covert));
	}

	/**
	 * 状态修改
	 */
	@PreAuthorize("@ss.hasPermi('system:user:edit')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/changeStatus")
	public Result changeStatus(@RequestBody SysUserUpdateParams user) {
		userService.checkUserAllowed(user);
		SysUserEntity covert = user.covert();
		covert.setUpdateBy(SecurityUtils.getUsername());
		return ok(userService.updateUserStatus(covert));
	}
	
	@GetMapping(value = {"/self"})
	public Result self() {
		return ok(SecurityUtils.getLoginUser());
	}
}
